﻿// -----------------------------------------------------------------------------
// DM 是 .NET 5 平台下开发管理的系统。
// Copyright © 2021 DM,  Co.,Ltd.
//
// 框架名称：Furion
// 后台框架：ABC.Admin
// -----------------------------------------------------------------------------

using Furion;

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace Tool
{
    public partial class WebHelper
    {
        /// <summary>
        /// 单文件上传
        /// </summary>
        /// <param name="typeName"></param>
        /// <param name="fileSize">文件上传大小，默认10M</param>
        /// <param name="fileExtensionName">文件上传扩展，默认全部文件格式</param>
        /// <returns></returns>
        public static ResultData<UploadReturn> FileUpload(string typeName, long fileSize = 10, string fileExtensionName = "*")
        {
            var resultdata = new ResultData<UploadReturn>();
            var context = App.GetService<IHttpContextAccessor>().HttpContext;
            var file = context.Request.Form.Files[0];
            if (file != null && !string.IsNullOrEmpty(file.FileName))
            {
                resultdata = FileUploadItem(file, typeName, fileSize, fileExtensionName);
            }
            return resultdata;
        }
        /// <summary>
        /// 同时上传多个文件
        /// </summary>
        /// <param name="typeName">类别名称</param>
        /// <param name="fileSize">文件上传大小，默认10M</param>
        /// <param name="fileExtensionName">文件上传扩展，默认全部文件格式</param>
        /// <returns></returns>
        public static ResultData<List<UploadReturn>> FileUploads(string typeName, long fileSize = 10, string fileExtensionName = "*")
        {
            var resultdata = new ResultData<List<UploadReturn>>();
            var context = App.GetService<IHttpContextAccessor>().HttpContext;
            foreach (var file in context.Request.Form.Files)
            {
                var rd = FileUploadItem(file, typeName, fileSize, fileExtensionName);
                if (rd.Succeeded == false)
                {
                    resultdata.Succeeded = false;
                    resultdata.Data = null;
                    resultdata.Errors = rd.Errors;
                    return resultdata;
                }
                else
                {
                    if (resultdata.Data == null) resultdata.Data = new List<UploadReturn>();
                    resultdata.Data.Add(rd.Data);
                }
            }

            resultdata.Succeeded = true;
            return resultdata;
        }
        /// <summary>
        /// 单文件上传
        /// </summary>
        /// <param name="typeName"></param>
        /// <param name="fileSize">文件上传大小，默认10M</param>
        /// <param name="fileExtensionName">文件上传扩展，默认全部文件格式</param>
        /// <returns></returns>
        private static ResultData<UploadReturn> FileUploadItem(IFormFile file, string typeName = "DefaultFiles", long fileSize = 10, string fileExtensionName = "*")
        {
            var resultdata = new ResultData<UploadReturn>();
            var webrootpath = App.WebHostEnvironment.WebRootPath;
            var context = App.GetService<IHttpContextAccessor>().HttpContext;
            if (file != null && !string.IsNullOrEmpty(file.FileName))
            {
                #region 判断大小
                //imgFile.Length (单位字节)
                var maxlength = fileSize * 1024 * 1024;//转换为字节
                //long mb = imgFile.Length / 1024 / 1024; // MB
                if (file.Length > maxlength)
                {
                    resultdata.Errors = $"上传文件超过{fileSize}MB";
                    return resultdata;
                }
                #endregion 判断大小

                var filename = ContentDispositionHeaderValue
                                .Parse(file.ContentDisposition)
                                .FileName.Trim("").Trim("\"");

                var extname = filename.Substring(filename.LastIndexOf("."), filename.Length - filename.LastIndexOf(".")); //扩展名，如.jpg

                #region 判断后缀
                //if (!extname.ToLower().Contains("jpg") && !extname.ToLower().Contains("png") && !extname.ToLower().Contains("gif"))
                //{
                //    return Json(new { code = 1, msg = "只允许上传jpg,png,gif格式的图片.", });
                //}
                if (fileExtensionName != "*" && !fileExtensionName.ToLower().Trim().Contains(extname.Trim().ToLower()))
                {
                    resultdata.Errors = $"文件上传格式错误，只允许上传{fileExtensionName}格式的文件！";
                    return resultdata;
                }
                #endregion



                var filename1 = $"{DateTime.Now:yyyyMMddHHmmss}" + extname;
                // 20210101
                string dir = DateTime.Now.ToString("yyyyMMdd");
                if (string.IsNullOrWhiteSpace(typeName))
                {
                    typeName = "DefaultFiles";//设置默认文件夹
                }
                // upload/{typeName}/20210101
                var path1 = Path.Combine("upload", typeName, dir);

                //完整物理路径，注意要用合作方无关目录分隔符
                string wuli_path = webrootpath + $"{Path.DirectorySeparatorChar}{path1}";
                if (!System.IO.Directory.Exists(wuli_path))
                {
                    System.IO.Directory.CreateDirectory(wuli_path);
                }
                filename = wuli_path + Path.DirectorySeparatorChar + filename1;

                using (FileStream fs = System.IO.File.Create(filename))
                {
                    file.CopyTo(fs);
                    fs.Flush();
                }
                resultdata.Succeeded = true;
                resultdata.Data = new UploadReturn()
                {
                    src = $"/{path1}/{filename1.Replace("\\", "/")}", //upload/{typeName}/20210101/xxxxx.png
                    httpsrc = $"{context.GetDomain()}/{path1.Replace("\\", "/")}/{filename1}"// http://www.xxx.com/upload/{typeName}/20210101/xxxxx.png
                };

            }
            return resultdata;
        }


        /// <summary>
        /// 删除文件返回
        /// </summary>
        public class UploadReturn
        {
            /// <summary>
            /// 相对路径
            /// </summary>
            public string src { get; set; }
            /// <summary>
            /// http完整路径
            /// </summary>
            public string httpsrc { get; set; }
        }


    }
}
